<?php

require_once 'MainPageWidget.php';
class VotesWidget extends MainPageWidget
{
	public $title = 'Голосование';

	public $vote = -1;

	public function settingsForm ()
	{
		$community_oid = $this->acl_assistant->acl_data['comity_oid'];

		$sql = "
		          SELECT
		          afeed.title as title,
		          afeed.oid as value
		          FROM       store_objects       AS objs
		          INNER JOIN store_class_allfeed AS afeed ON afeed.oid = objs.oid
		                       AND afeed.is_deleted = 0 AND afeed.community_oid = ".$community_oid."
		          INNER JOIN t_acl_tree tat ON tat.id_object =  objs.oid  AND tat.is_deleted = 0
		          WHERE  objs.type='fvote'
		          ORDER BY objs.ctime DESC";

		$result = $this->ctx->db->query($sql);
		// --- tdis to form fields ---  }}}
		$config['form'] = array(
		'title' => 'Настройка голосования',
		'fields' => array(

		'title' => array(
		'type' => 'text',
		'title' => 'Название',
		'default' => $this->title,
		'description' => 'Название голосования',
		),

		'vote' => array(
		'type' => 'select',
		'title' => 'Голосование',
		'default' => $this->getParam('vote', -1),
		'options' => $result,
		),
		),
		);
		return $config['form'];
	}

	public function Render() {

		$aa = $this->acl_assistant;
		$aa->getInfo();

		$voteId = $this->getParam('vote', -1);
		$rights = $aa->getAvailableOperations();
		if($voteId != -1) {
			//подключаем итем текущего голосования чтобы узнать все его(голосования) параметры
			$im = $this->ctx->mm->getModel("Item", "m");
			$vo = $im->getItem($voteId);

			if($vo)	{
				$content['answers'] = $vo->data['answers'];

				//Подключаем модель голосования
				$vm = $this->ctx->mm->getModel("Vote","m");

				$cdate_till = RL_CyrDate::newFromStr("%Y-%m-%d", $vo->data['date_till']);

				if ($cdate_till && ($cdate_till->unix_mark() <= RL_CyrDate::newNow()->unix_mark()) ) {
					$content['vote_closed'] = true;
				}

				// Проверяем голосовал ли юзер в этом голосовании и его права на голосование
				$max_voters = 0;
				$overall_voters = 0;
				if ( $content['vote_closed']
				|| ($vm->checkUserVote($voteId, $aa->acl_data['user_id'])) || (!isset($rights['comment_create'])))
				{
					$this->isVoted = 1;
					foreach($content['answers'] as &$answ){
						$votes = $vo->data['votes'][$answ['num']];
						$answ['votes'] = $votes?$votes:0;

						if ($max_voters < $answ['votes']) $max_voters = $answ['votes'];
						$overall_voters += $votes;
					}

				} else {
					$this->isVoted = 0;
				}

				if ($vo->data['posted_by_id'] == $aa->acl_data['user_id']) {
					if ( $content['vote_closed'] ) {
						$content['can_open'] = 1;
					} else {
						$content['can_close'] = 1;
					}
				}

				$ug = new RL_URLGenerator($this->ctx->rh->router->getRule("vote_manager"));
				$ug->setRouter($this->ctx->rh->router);

				$ug->setParams(array(
				"community_url"=>$this->params['community_url'],
				"id_item"=>$voteId,
				)
				);
				$content['vote_url'] = $ug->generateUrl();
			}

			$content['title'] = $this->getParam("title", "Голосование");
			$content['name'] = $vo->data['title'];
			$content['question'] = $vo->data['question'];
			$content['max_voters'] = $max_voters;
			$content['overall_voters'] = $overall_voters;
			$content['can_vote'] = (isset($aa->acl_data['user_id'])) ? true : false;
			$this->content = $content;
		} else {
			//Виджет не настроен
			$this->tdi_not_found = 1;
		}
		return $this;
	}

	public function ajax_closeVote() {
		$aa = $this->acl_assistant;
		$aa->getInfo();

		$this->ctx->rh->UseClass("Model_Item");
		$vm = $this->ctx->mm->getModel("Vote","m");
		$voteId = $this->getParam('vote', -1);

		if ( !empty($voteId) ) {
			$rights = $aa->getAvailableOperations();

			if ( isset($rights['item_edit']) ) {
				$vm->closeVote($voteId);
			}
		}

		$view = $this->ctx->rh->views->findByName('WG_VotesWidget');
		$this->render();

		$view->data['widget'] = $this;

		return array('html'=>$view->getContent(), 'vote_message'=>'');
	}

	public function ajax_openVote() {
		$aa = $this->acl_assistant;
		$aa->getInfo();

		$this->ctx->rh->UseClass("Model_Item");
		$vm = $this->ctx->mm->getModel("Vote","m");
		$voteId = $this->getParam('vote', -1);

		if ( !empty($voteId) ) {
			$rights = $aa->getAvailableOperations();

			if ( isset($rights['item_edit']) ) {
				$vm->openVote($voteId);
			}
		}

		$view = $this->ctx->rh->views->findByName('WG_VotesWidget');
		$this->render();

		$view->data['widget'] = $this;

		return array('html'=>$view->getContent(), 'vote_message'=>'');
	}

	public function ajax_Vote($vote_variant) {
		$aa = $this->acl_assistant;
		$aa->getInfo();

		$this->ctx->rh->UseClass("Model_Item");
		$vm = $this->ctx->mm->getModel("Vote","m");
		$voteId = $this->getParam('vote', -1);

		//Проверяем права юзера на голосование
		$rights = $aa->getAvailableOperations();
		if(isset($rights['comment_create']))
		{
			//Проверяем голосовал ли пользователь
			if(!$vm->checkUserVote($voteId, $aa->acl_data['user_id']))
			{
				$this->ctx->db->begin();
				//добавляем голос
				$st = $vm->addUserVote($voteId, $vote_variant, $aa->acl_data['user_id']);
				if ($st) {
					$im = $this->ctx->mm->getModel("Item", "m");
					$vo = $im->getItem($voteId);

					// запостить комментарий
					$cm = $this->ctx->mm->getModel("Comment", "m");
					$fcomment = $cm->submitComment( 'Проголосовал за вариант "'. $vo->data['answers'][$vote_variant]['text'] .'"', $voteId, $aa->acl_data['user_id'], 1 );
					if ($fcomment) {
						$aa->createComment( $fcomment->id, $voteId );
					}

					if (!$this->ctx->db->isErrorInTransaction()) {
						$vote_message = 'Спасибо! Ваш голос учтен.';
					}
					else {
						$vote_message = "DB Transaction rollback";
					}
				}
				$this->ctx->db->end();
			}else
			{
				$vote_message = 'Вы уже проголосовали!';
			}
		}else
		{
			$vote_message = 'У вас нет прав на голосование.';
		}
		//Вытаскиваем шаблон виджета и рендерим его
		$view = $this->ctx->rh->views->findByName('WG_VotesWidget');
		$this->render();

		$view->data['widget'] = $this;

		return array('html'=>$view->getContent(), 'vote_message'=>$vote_message);
	}

}

